package com.zxc.shortlink.controller;

import com.zxc.shortlink.component.ThreadPoolComponent;
import com.zxc.shortlink.controller.request.LinkMappingRequest;
import com.zxc.shortlink.service.LinkMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
* @author zxc_user
* @date 2022/3/23 23:31
* @version 1.0
* @description LinkMappingMapper控制器
**/
@RestController
@RequestMapping("/linkMapping")
@Slf4j
public class LinkMappingMapperController {

    @Resource
    private LinkMappingService linkMappingService;
    @Resource
    private ThreadPoolComponent threadPoolComponent;

    @PostMapping("/create")
    public ResponseEntity<Boolean> create(@Valid @RequestBody LinkMappingRequest linkMappingRequest) throws IOException {
       // AsyncContext asyncContext = request.startAsync();
        return ResponseEntity.ok(linkMappingService.saveLinkMapping(linkMappingRequest));
    }

    @GetMapping("/{shortLink}")
    public void shortLink(@PathVariable("shortLink") String shortLink, HttpServletResponse response) throws IOException {
        try {
            //获取链接
            String originLink = linkMappingService.getOriginLinkByShortLink(shortLink);
            //重定向
            response.sendRedirect(originLink);
        }catch (Exception e) {
            log.error("获取不到链接", e);
            response.getWriter().write("unknow the short link" + shortLink);
        }
    }

}
